package com.action;

import com.bean.ResponseBean;
import com.pojo.*;
import com.service.LoginService;
import com.service.WuyeService;
import com.util.IPUtil;
import com.util.JwtUtil;
import com.util.PasswordUtil;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("login")
@RestController
public class LoginAction {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate ;

    @Autowired
    private LoginService loginService ;

    @Autowired
    private WuyeService wuyeService;
    /**
     * 物业登录
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("wuye")
    public ResponseBean wuye(String username , String password , HttpServletRequest request){
        //获取ip
        String ip = IPUtil.getIpAddr(request);


        //从redis里取登录失败次数
        BoundValueOperations b = redisTemplate.boundValueOps(ip);
        if ("-1".equals(b.get())) {
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        if (!redisTemplate.hasKey(ip)) {
            b.set("1");
            b.expire(60, TimeUnit.SECONDS);
            //登录失败次数小于十，次数加一
        } else if (Integer.parseInt(b.get().toString()) < 10) {
            int tmp = Integer.parseInt(b.get().toString());
            b.set(String.valueOf(++tmp));
            b.expire(60, TimeUnit.SECONDS);
            //大于十，参数为-1,并一分钟内禁止登录
        } else {
            b.set("-1");
            b.expire(60, TimeUnit.SECONDS);
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        String pwd = PasswordUtil.jiami(password);
        Wuye wuye = loginService.wuyeLogin(username, pwd);

        if (wuye != null && wuye.getStatus() == 1) {
            Map map = new HashMap();
            map.put("token", JwtUtil.generToken(wuye.getId(), null, null));
            map.put("wuyename", wuye.getWyname());
            map.put("id", wuye.getId());
            return new ResponseBean(200,"登录成功",map);
        }
        if (wuye == null) {
            return ResponseBean.error("用户名或密码错误");
        }
        return ResponseBean.error("用户已禁用");
    }

    /**
     * 企业登录
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("qiye")
    public ResponseBean qiye(String username , String password , HttpServletRequest request){
        //获取ip
        String ip = IPUtil.getIpAddr(request);


        //从redis里取登录失败次数
        BoundValueOperations b = redisTemplate.boundValueOps(ip);
        if ("-1".equals(b.get())) {
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        if (!redisTemplate.hasKey(ip)) {
            b.set("1");
            b.expire(60, TimeUnit.SECONDS);
            //登录失败次数小于十，次数加一
        } else if (Integer.parseInt(b.get().toString()) < 10) {
            int tmp = Integer.parseInt(b.get().toString());
            b.set(String.valueOf(++tmp));
            b.expire(60, TimeUnit.SECONDS);
            //大于十，参数为-1,并一分钟内禁止登录
        } else {
            b.set("-1");
            b.expire(60, TimeUnit.SECONDS);
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        String pwd = PasswordUtil.jiami(password);
        Qiye admin = loginService.qiyeLogin(username, pwd);

        if (admin != null && admin.getStatus() == 1) {
            request.getSession().setAttribute("qiye", admin);
            return ResponseBean.ok("登录成功");
        }

        if (admin == null) {
            return ResponseBean.error("用户名或密码错误");
        }

        return ResponseBean.error("账户异常，请联系管理员");
    }

    /**
     * 充值点登录
     * @author zxj
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("recharge")
    public ResponseBean recharge(String username , String password , HttpServletRequest request){
        //获取ip
        String ip = IPUtil.getIpAddr(request);


        //从redis里取登录失败次数
        BoundValueOperations b = redisTemplate.boundValueOps(ip);
        if ("-1".equals(b.get())) {
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        if (!redisTemplate.hasKey(ip)) {
            b.set("1");
            b.expire(60, TimeUnit.SECONDS);
            //登录失败次数小于十，次数加一
        } else if (Integer.parseInt(b.get().toString()) < 10) {
            int tmp = Integer.parseInt(b.get().toString());
            b.set(String.valueOf(++tmp));
            b.expire(60, TimeUnit.SECONDS);
            //大于十，参数为-1,并一分钟内禁止登录
        } else {
            b.set("-1");
            b.expire(60, TimeUnit.SECONDS);
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        String pwd = PasswordUtil.jiami(password);
        RechargeStation rechargeStation = loginService.rechargeStationLogin(username, pwd);

        if (rechargeStation != null && rechargeStation.getStatus() == 1) {
            request.getSession().setAttribute("rechargeStation", rechargeStation);
            return ResponseBean.ok("登录成功");
        }

        if (rechargeStation == null) {
            return ResponseBean.error("用户名或密码错误");
        }

        return ResponseBean.error("账户异常，请联系管理员");
    }


    /**
     * 证件管理登录
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("certificate")
    public ResponseBean certificate(String username , String password , HttpServletRequest request){
        //获取ip
        String ip = IPUtil.getIpAddr(request);

        //从redis里取登录失败次数
        BoundValueOperations b = redisTemplate.boundValueOps(ip);
        if ("-1".equals(b.get())) {
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        if (!redisTemplate.hasKey(ip)) {
            b.set("1");
            b.expire(60, TimeUnit.SECONDS);
            //登录失败次数小于十，次数加一
        } else if (Integer.parseInt(b.get().toString()) < 10) {
            int tmp = Integer.parseInt(b.get().toString());
            b.set(String.valueOf(++tmp));
            b.expire(60, TimeUnit.SECONDS);
            //大于十，参数为-1,并一分钟内禁止登录
        } else {
            b.set("-1");
            b.expire(60, TimeUnit.SECONDS);
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        String pwd = PasswordUtil.jiami(password);
        CertificateUser certificateUser = loginService.certificateUserLogin(username, pwd);

        if (certificateUser != null && certificateUser.getStatus() == 1) {
            request.getSession().setAttribute("certificateUser", certificateUser);
            return ResponseBean.ok("登录成功");
        }

        if (certificateUser == null) {
            return ResponseBean.error("用户名或密码错误");
        }

        return ResponseBean.error("账户异常，请联系管理员");
    }

    /**
     * 每5秒取session，判断是否登录
     */
    @RequestMapping("pandeng_certificate")
    public ResponseBean panDengByCertificate(HttpServletRequest request){
        CertificateUser userinfo = (CertificateUser) request.getSession().getAttribute("certificateUser") ;
        if(userinfo==null){
            return new ResponseBean(1,1,"请先登录！",null);
        }else{
            return new ResponseBean(0,1,"已登录！",userinfo.getLoginName());
        }
    }

    /**
     * 每5秒取session，判断是否登录
     */
    @RequestMapping("pandeng_wuye")
    public ResponseBean panDeng(@RequestHeader(value = "token" , required = false) String token){
        String msg = wuyeService.verifyToken(token);
        if (StringUtil.isNotNull(msg)){
            return ResponseBean.error(msg);
        }
        String uid = JwtUtil.getUsername(token);
        Wuye wuye = wuyeService.getById(uid);
        if(wuye == null){
            return ResponseBean.error("请先登录！");
        }else{
            return new ResponseBean(200,"已登录！",wuye.getWyname());
        }
    }


    /**
     * 每5秒取session，判断是否登录
     */
    @RequestMapping("pandeng_business")
    public ResponseBean panDengByBusiness(HttpServletRequest request){
        Business userinfo = (Business) request.getSession().getAttribute("business") ;
        if(userinfo==null){
            return new ResponseBean(1,1,"请先登录！",null);
        }else{
            return new ResponseBean(0,1,"已登录！",userinfo.getName());
        }
    }

    /**
     * 每5秒取session，判断是否登录
     */
    @RequestMapping("pandeng_rechargeStation")
    public ResponseBean panDengByRechargeStation(HttpServletRequest request){
        RechargeStation userinfo = (RechargeStation) request.getSession().getAttribute("rechargeStation") ;
        if(userinfo==null){
            return new ResponseBean(1,1,"请先登录！",null);
        }else{
            return new ResponseBean(0,1,"已登录！",userinfo.getName());
        }
    }



    /**
     * 物业修改密码
     * @param oldPwd
     * @param newPwd
     * @param request
     * @return
     */
    @RequestMapping("wy_update_password")
    public ResponseBean updatePassword(String oldPwd , String newPwd , HttpServletRequest request){
        Wuye wuye = (Wuye) request.getSession().getAttribute("wuye") ;

        if(StringUtil.isNull(oldPwd)) {
            return ResponseBean.error("请输入旧密码") ;
        }
        if(StringUtil.isNull(newPwd)) {
            return ResponseBean.error("请输入新密码") ;
        }
        String res = loginService.wyUpdatePassword(oldPwd , newPwd , wuye.getId()) ;

        return res == null ? ResponseBean.OK : ResponseBean.error(res) ;
    }


    /**
     * 商户修改密码
     * @param oldPwd
     * @param newPwd
     * @param request
     * @return
     */
    @RequestMapping("business_update_password")
    public ResponseBean updatePasswordByBusiness(String oldPwd , String newPwd , HttpServletRequest request){
        Business business = (Business) request.getSession().getAttribute("business") ;

        if(StringUtil.isNull(oldPwd)) {
            return ResponseBean.error("请输入旧密码") ;
        }
        if(StringUtil.isNull(newPwd)) {
            return ResponseBean.error("请输入新密码") ;
        }
        String res = loginService.businessUpdatePassword(oldPwd , newPwd , business.getId()) ;

        return res == null ? ResponseBean.OK : ResponseBean.error(res) ;
    }

    /**
     * 充值点修改密码
     * @param oldPwd
     * @param newPwd
     * @param request
     * @return
     */
    @RequestMapping("rechargeStation_update_password")
    public ResponseBean updatePasswordByRechargeStation(String oldPwd , String newPwd , HttpServletRequest request){
        RechargeStation rechargeStation = (RechargeStation) request.getSession().getAttribute("rechargeStation") ;

        if(StringUtil.isNull(oldPwd)) {
            return ResponseBean.error("请输入旧密码") ;
        }
        if(StringUtil.isNull(newPwd)) {
            return ResponseBean.error("请输入新密码") ;
        }
        String res = loginService.rechargeStationUpdatePassword(oldPwd , newPwd , rechargeStation.getId()) ;

        return res == null ? ResponseBean.OK : ResponseBean.error(res) ;
    }

    /**
     * 证件管理用户修改密码
     * @param oldPwd
     * @param newPwd
     * @param request
     * @return
     */
    @RequestMapping("certificate_update_password")
    public ResponseBean updatePasswordByCertificate(String oldPwd , String newPwd , HttpServletRequest request){
        CertificateUser certificateUser = (CertificateUser) request.getSession().getAttribute("certificateUser") ;

        if(StringUtil.isNull(oldPwd)) {
            return ResponseBean.error("请输入旧密码") ;
        }
        if(StringUtil.isNull(newPwd)) {
            return ResponseBean.error("请输入新密码") ;
        }
        String res = loginService.certificateUseUpdatePassword(oldPwd , newPwd , certificateUser.getId()) ;

        return res == null ? ResponseBean.OK : ResponseBean.error(res) ;
    }


    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping("logout")
    public ResponseBean logout(HttpServletRequest request){
        request.getSession().invalidate();
        return ResponseBean.OK;
    }

}
